import { useState } from 'react';
import { Input } from 'antd';

const reg = /^(([1-9][0-9]*)|(([0]\.\d{0,}|[1-9][0-9]*\.\d{0,})))$/;

export const CustomInputNumber = ({ disabled, defaultValue = '', placeholder = '请输入', precision = 2, handleChange }) => {

  if(![2, 3].includes(precision)){
    throw Error('此处暂且只支持2位，3位小数');
  }

  const [value, setValue] = useState(defaultValue);

  const onChange = (e) => {
    const input = e.target.value;
    if (reg.test(input) || input == 0) {
      setValue(input);
    } 
  };

  const onBlur = (e) => {
    const formatValue = Number(e.target.value).toFixed(precision);
    setValue(formatValue);
    handleChange?.(formatValue);
  }

  return <Input disabled={disabled} value={value} placeholder={placeholder} onChange={onChange} onBlur={onBlur} />
}


export const IntInputNumber = ({ disabled, defaultValue = '', placeholder = '请输入', handleChange, onPressEnter, checkFunc }) => {

  const [value, setValue] = useState(defaultValue);

  const onChange = (e) => {
    const input = e.target.value;
    if ((/^\+?[1-9]\d*$/.test(input) && (!checkFunc || checkFunc(input))) || input === '') {
      setValue(input);
      handleChange(input)
    } 
  };

  const onBlur = (e) => {
    const formatValue = Number(e.target.value) || '';
    setValue(formatValue);
    handleChange?.(formatValue);
  }

  return <Input disabled={disabled} value={value} placeholder={placeholder} onChange={onChange} onBlur={onBlur} onPressEnter={onPressEnter}/>
}
